package entity

import (
	"encoding/json"
	"time"
)

//
type Quest struct {
	RoleID int32 `gorm:"type:int;primary_key"`
	Date   int32 // 活动开启的日期
	//InitPower int64
	Data1     []byte `gorm:"type:jsonb"` // json.Marshal(self.data1)\
	Data2     []byte `gorm:"type:jsonb"` // json.Marshal(self.data2)
	CreatedAt time.Time
	UpdatedAt time.Time

	data1 map[int32]int64 `sql:"-"` // 类型 => 数量
	data2 map[int32]bool  `sql:"-"` // ActivityID => 已完成
}

func (Quest) TableName() string {
	return "act_quests"
}

func (e *Quest) Init(date int32) {
	e.data1 = make(map[int32]int64)
	e.data2 = make(map[int32]bool)
	e.Date = date
	//e.InitPower = power
}

func (e *Quest) AfterFind() error {

	e.data1 = make(map[int32]int64)
	e.data2 = make(map[int32]bool)
	_ = json.Unmarshal(e.Data1, &e.data1)
	_ = json.Unmarshal(e.Data2, &e.data2)
	return nil
}

func (e *Quest) BeforeSave() error {

	if e.data1 == nil {
		e.data1 = make(map[int32]int64)
	}
	if e.data2 == nil {
		e.data2 = make(map[int32]bool)
	}

	e.Data1, _ = json.Marshal(e.data1)
	e.Data2, _ = json.Marshal(e.data2)
	return nil
}

func (e *Quest) BeforeUpdate() error {

	if e.data1 == nil {
		e.data1 = make(map[int32]int64)
	}
	if e.data2 == nil {
		e.data2 = make(map[int32]bool)
	}

	e.Data1, _ = json.Marshal(e.data1)
	e.Data2, _ = json.Marshal(e.data2)
	return nil
}

func (e *Quest) GetValue(Type int32) int64 {
	return e.data1[Type]
}

func (e *Quest) SetValue(Type int32, value int64) {
	e.data1[Type] = value
}

func (e *Quest) AddValue(Type int32, value int64) {
	e.data1[Type] = e.data1[Type] + value
}

func (e *Quest) IsFinish(ID int32) bool {
	return e.data2[ID]
}

func (e *Quest) SetFinish(ID int32) {
	e.data2[ID] = true
}
